import { createRouter, createWebHashHistory } from 'vue-router'
import { ElMessageBox } from '_element-plus@1.0.2-beta.71@element-plus'
import  {login}  from '../api/auth'
const routes = [{
    path: "/",
    redirect: "/home"
}, {
    path: '/home',
    name: 'home',
    component: () => import('../views/home.vue')
}, {
    path: '/programming',
    name: 'programming',
    component: () => import('../views/Programming.vue')
}, {
    path: '/entertainment',
    name: 'entertainment',
    component: () => import('../views/Entertainment.vue')
}, {
    path: '/interests',
    name: 'interests',
    component: () => import('../views/Interests.vue')
}, {
    path: '/others',
    name: 'others',
    component: () => import('../views/Others.vue')
}, {
    path: '/articleSearch',
    name: 'articleSearch',
    component: () => import('../views/ArticleSearch.vue')
}, {
    path: '/articles/:id/detail',
    name: 'articleDetail',
    component: () => import('../views/ArticleDetail.vue'),
    props: true
}, {
    path: '/admin',
    name: 'admin',
    component: () => import('../views/admin/Admin.vue'),
    meta: {
        auth: true
    },
    children: [
        {
            path: 'articles',
            name: 'articles',
            component: () => import('../views/admin/ArticleList.vue')
        }, {
            path: 'articleCreation',
            name: 'articleCreation',
            component: () => import('../views/admin/ArticleCreation.vue')
        },
        {
            path: 'tags',
            name: 'tags',
            component: () => import('../views/admin/Tags.vue')
        },
        {
            path: 'categories',
            name: 'categories',
            component: () => import('../views/admin/Categories.vue')
        },
        {
            path: 'comments',
            name: 'comments',
            component: () => import('../views/admin/Comments.vue')
        }
    ]
}]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

router.beforeEach((to, from, next) => {

    localStorage.setItem("currentPath", to.fullPath)
    if (to.meta.auth && localStorage.token == undefined) {
        ElMessageBox.alert("尚未登录，现在登录吗？", "登录验证", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            showCancelButton: true,
            type: 'warning'
        }).then(() => {
            ElMessageBox.prompt("请输入用户名和密码", "登录", {
                confirmButtonText: "登录",
                cancelButtonText: "取消",
            }).then(({ value }) => {
                console.log("credential", value);
                login(value).then(res => {
                    next()
                })
            }).catch()
        }).catch()
    } else {
        next()
    }
})

export default router
